package com.accelstack.cmp.controller;

import com.accelstack.cmp.security.TokenManager;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

/**
 * Token信息控制器
 */
@Tag(name = "Token管理", description = "Token相关查询接口")
@RestController
@RequestMapping("/api/token")
@RequiredArgsConstructor
public class TokenInfoController {
    
    private final TokenManager tokenManager;
    
    @Operation(summary = "获取Token信息", description = "获取当前Token的详细信息和剩余有效时间")
    @GetMapping("/info")
    public ResponseEntity<Map<String, Object>> getTokenInfo(
            @Parameter(description = "Token", required = true) 
            @RequestHeader("x-auth-token") String token) {
        
        Map<Object, Object> tokenInfo = tokenManager.getTokenInfo(token);
        Long ttl = tokenManager.getTokenTTL(token);
        
        Map<String, Object> response = new HashMap<>();
        response.put("token", token.substring(0, 8) + "..." + token.substring(token.length() - 8));
        response.put("username", tokenInfo.get("username"));
        response.put("accessKey", tokenInfo.get("accessKey"));
        response.put("createTime", tokenInfo.get("createTime"));
        response.put("ttl", ttl);
        response.put("ttlHours", ttl / 3600.0);
        response.put("expiresIn", ttl * 1000);
        
        return ResponseEntity.ok(response);
    }
    
    @Operation(summary = "获取当前用户信息", description = "从SecurityContext获取当前认证用户信息")
    @GetMapping("/current-user")
    public ResponseEntity<Map<String, Object>> getCurrentUser() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        
        Map<String, Object> userInfo = new HashMap<>();
        if (authentication != null && authentication.isAuthenticated()) {
            userInfo.put("authenticated", true);
            userInfo.put("username", authentication.getName());
            userInfo.put("authorities", authentication.getAuthorities());
        } else {
            userInfo.put("authenticated", false);
        }
        
        return ResponseEntity.ok(userInfo);
    }
}

